package com.yonyou.ucf.mdf;

import com.yonyou.cloud.inotify.client.NotifyStub;
import com.yonyou.iuap.yonscript.support.filter.J2v8DebugHelperFilter;
import com.yonyou.diwork.config.DiworkEnv;
import com.yonyou.iuap.ucf.multilang.runtime.utils.MlRemoteTool;
import com.yonyou.iuap.yms.id.config.EnableYmsOid;
import com.yonyou.ucf.mdd.common.configruation.PartitionConfig;
import com.yonyou.ucf.mdd.ext.bill.config.BillMetaConditionalConfig;
import com.yonyou.ucf.mdd.ext.config.MetaConditionalConfig;
import com.yonyou.ucf.mdd.ext.config.OptionConditionalConfig;
import com.yonyou.ucf.mdd.ext.config.RefConditionConfig;
import com.yonyou.ucf.mdd.ext.config.TenantConditionalConfig;
import com.yonyou.ucf.mdd.ext.config.billforeignkeybiz.RuleRegisterConditionalConfig;
import com.yonyou.ucf.mdd.ext.i18n.service.impl.MddMultiLangBillMetaServiceImpl;
import com.yonyou.ucf.mdf.app.ApplicationProperties;
import com.yonyou.ucf.mdf.app.controller.interceptor.PrintFilter;
import com.yonyou.ucf.mdf.sdk.rest.util.PropertyUtil;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.OpenApiISVRouterAutoConfiguration;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.imeta.spring.support.profile.DomainIsolationPropertyProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;


/**
 * spring-boot 入口类
 */
@Slf4j
@EnableYmsOid
@EnableScheduling //开启定时任务
@EnableConfigurationProperties(ApplicationProperties.class)
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, RabbitAutoConfiguration.class})
@ComponentScan(basePackages = {"com.yonyou", "com.yonyoucloud"},
        excludeFilters = {@ComponentScan.Filter(type = FilterType.REGEX,
                pattern = {"com.yonyoucloud.uretail.*",// "com.yonyou.ucf.mdd.poi.service.POIService",
                        "com.yonyou.ucf.mdd.core.file.oss.*", "com.yonyou.ucf.mdd.ext.bill.controller.BillController", "com.yonyou.ucf.mdd.ext.bill.controller.BillPrintController",
                        "com.yonyou.ucf.mdd.ext.base.controller.RegionController",
                        "com.yonyou.ucf.mdd.ext.sys.controller.LoginController",
                        "com.yonyou.ucf.mdd.ext.sys.controller.CacheController",
                        "com.yonyou.ucf.mdd.conf.MddBizDataMybatisConfig",
                        "com.yonyou.ucf.mdd.ext.aop.AuthServiceContextAop",
                        "com.yonyou.ucf.mdd.ext.sys.controller.UserController",
                        "com.yonyou.ucf.mdd.ext.bill.meta.controller.MetaModelController",
                        "com.yonyou.ucf.mdd.ext.filter.controller.FilterDesignController",
                        "com.yonyou.ucf.mdd.ext.bpm.controller.BpmController",
                        "com.yonyou.ucf.mdd.ext.bill.rule.crud.SaveBillRule",
                        "com.yonyou.ucf.mdd.ext.bill.rule.crud.DeleteBpmRule",
                        "com.yonyou.ucf.mdd.ext.bill.rule.enhance.EnhanceSaveBillRule",
                        "com.yonyou.ucf.mdd.rules.MddReferDataRule",
                        "com.yonyou.ucf.mdd.bpm.service.ProcessService",
                        "com.yonyou.iuap.ucf.search.UcfSearchSpringInitiator",
                        "com.yonyou.ucf.mdd.core.developer.DeveloperController",
                        "com.yonyou.ucf.mdd.core.service.RPCServiceAdapterImpl",
                        "com.yonyou.diwork.multilingual.service.ILanguageService",
                        "com.yonyou.ucf.mdd.ext.poi.importbiz.service.impl.ImportSaveServiceImpl"})})
@EnableAsync
@Import({ MetaConditionalConfig.class, OptionConditionalConfig.class, RefConditionConfig.class, BillMetaConditionalConfig.class, TenantConditionalConfig.class, PartitionConfig.class,
        RuleRegisterConditionalConfig.class, OpenApiISVRouterAutoConfiguration.class})
@ImportResource({DiworkEnv.DIWORK_CONFIG_XML,"classpath*:/config/applicationContext*.xml","classpath*:/spring-sub/applicationContext*.xml","classpath:applicationContext-imeta.xml", "classpath:applicationContext-billNumber-service.xml", "classpath:applicationContext-common.xml", "classpath:applicationContext-db.xml", "classpath:applicationContext-redis.xml", "classpath:applicationContext-bill-service.xml"})
@ServletComponentScan
public class MDFApplication extends SpringBootServletInitializer {
    public static void main(String[] args) throws Exception {
        ApplicationContext app = SpringApplication.run(MDFApplication.class, args);
//        NotifyStub.start();
    }

    @SneakyThrows
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        // 注意这里要指向原先用main方法执行的Application启动类
        SpringApplicationBuilder applicationBuilder = builder.sources(MDFApplication.class);

        MlRemoteTool.init(PropertyUtil.getProperty("spring.profile"));//初始化多语配置
        // 缓存通知配置
//        NotifyStub.start();
        return applicationBuilder;
    }

    /**
     * 处理远程参照查询问题,否则会到本地库查询
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public DomainIsolationPropertyProfile domainIsolationPropertyProfile() {
        return new DomainIsolationPropertyProfile();
    }


    @Bean
    @ConditionalOnMissingBean
    public MddMultiLangBillMetaServiceImpl mddMultiLangBillMetaService() {
        return new MddMultiLangBillMetaServiceImpl();
    }

    @Bean
    public FilterRegistrationBean printFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new PrintFilter());
        registrationBean.addUrlPatterns("/print/printdelegate");
        return registrationBean;
    }

    @Value("${access.key}")
    private String key;
    @Value("${access.secret}")
    private String secret;

    /**
     * J2v8 debugHelper
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean debugHelperFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new J2v8DebugHelperFilter());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }

//    private void initializeEnvironment()throws NoSuchFieldException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException{
//        Field environmentField = AppRuntimeEnvironment.class.getDeclaredField("environment");
//        environmentField.setAccessible(true);
//        Class<?> environmentClass = Class.forName("com.yonyou.cloud.middleware.Environment");
//        Constructor<?> constructor = environmentClass.getDeclaredConstructor(String.class,String.class,String.class,String.class,String.class,String.class,String.class,
//                List.class,String.class,String.class);
//        constructor.setAccessible(true);
//        Environment environment = (Environment) constructor.newInstance(null,null,key,secret,null,null,null,null,null,null);
//        environmentField.set(null,environment);
//    }


}